//
//  VCForMVPlayerOfFirst.m
//  Movie
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "VCForMVPlayerOfFirst.h"
#import <AVFoundation/AVFoundation.h>
#import "SVProgressHUD.h"
#import "MovieModel.h"
#import "DataBaseHandle.h"
#import "MusicPlayerViewController.h"

@interface VCForMVPlayerOfFirst ()<stop>

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)UIView *movieView;
@property(nonatomic,strong)UIView *shadeView;

@property(nonatomic,assign)BOOL isCollect;
@property(nonatomic,strong)UIView *ControlView;
@property(nonatomic,strong)UIButton *CollectButton;
@property(nonatomic,assign)BOOL isPause;  // 判断暂停
@property(nonatomic,strong)UIButton *pauseButton;
@property(nonatomic,strong)UIButton *backButton;
@property(nonatomic,strong)UILabel *startTimeLabel;   // 开始时间
@property(nonatomic,strong)UIButton *volumeDownbutton;  // 音量减
@property(nonatomic,strong)UISlider *timeSlider;  //时间条
@property(nonatomic,strong)UIButton *uploadButton;
@property(nonatomic,strong)UIButton *volumeUpbutton;  //音量加
@property(nonatomic,strong)UILabel *allTimeLabel;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIProgressView *progress;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)CGFloat currentTime;   // 当前视角
@property(nonatomic,strong)AVPlayerLayer *playerLayer;
@property(nonatomic,strong)UIProgressView *buffer;
@property(nonatomic,strong)UIWebView *lodingGif;

@property(nonatomic,strong)UIView *adView;

/** 缓冲进度条 */
@property(nonatomic,strong)UIView *bufferView;
/** playItem时间刻度 */
@property(nonatomic,assign)int timeScale;

///时间后台
@property(nonatomic,strong)id obj;
//自动布局用的字典
@property(nonatomic,strong)NSDictionary *views;
#define screenFrame [UIScreen mainScreen].bounds

@end

@implementation VCForMVPlayerOfFirst

-(void)stopPlay{
    if( [UIApplication sharedApplication].applicationState == UIApplicationStateActive ) {
        
        [self.player play];
    }
    else{
        [self.player pause];
    }
}

-(void)play{
    if( [UIApplication sharedApplication].applicationState == UIApplicationStateActive ) {
        
        [self.player play];
    }
    else{
        [self.player pause];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithRed:40 / 255.f green:40 / 255.f blue:40 / 255.f alpha:1];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlay) name:@"stop" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(play) name:@"stop" object:nil];
    
    self.movieView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1000,1000)];
    self.movieView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.movieView];
    
    self.shadeView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.movieView addSubview:self.shadeView];

    //网络
    NSURL *playURl = [NSURL URLWithString:self.urlForPlay];
    
    AVAsset *asset = [AVAsset assetWithURL:playURl];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    self.player = [AVPlayer playerWithPlayerItem:item];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, screenFrame.size.height, screenFrame.size.width);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.movieView.layer addSublayer:self.playerLayer];
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];//监听属性
    [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [self setUpControllView];
    self.ControlView.hidden = 1;
    self.shadeView.hidden = 1;
    self.isCollect = 0;
    [SVProgressHUD show];
    [SVProgressHUD setBackgroundColor:[UIColor grayColor]];
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}


- (void)setUpControllView{
    
    self.ControlView = [[UIView alloc]init];
    self.player.volume = 2;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(refondContr:) userInfo:nil repeats:NO];
    self.ControlView.frame = CGRectMake(0, 0, screenFrame.size.height, screenFrame.size.width);
    
    [self.view addSubview:self.ControlView];
    
    //播放进度条
    self.timeSlider = [[UISlider alloc] init];
    UIImage *image1 = [UIImage imageNamed:@"slider@2x.png"];
    self.timeSlider.frame = CGRectMake(48, self.ControlView.frame.size.height - 25, self.ControlView.frame.size.width - 96, 2);
    [self.timeSlider setThumbImage:image1 forState:UIControlStateNormal];
    self.timeSlider.minimumTrackTintColor = [UIColor colorWithRed:187 / 255.f green:255 / 255.f blue:255 / 255.f alpha:0.3];
    self.timeSlider.maximumTrackTintColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.3];
//    self.timeSlider.translatesAutoresizingMaskIntoConstraints = NO;
    
    ///关闭了交互
    //    [_timeSlider setUserInteractionEnabled:0];
    [self.timeSlider addTarget:self action:@selector(changeProgress:)
          forControlEvents:UIControlEventValueChanged];
    
    self.timeSlider.maximumValue = self.receiveModel.duration;
    //        [_timeSlider addTarget:self action:@selector(StartDrag:) forControlEvents:UIControlEventTouchDown];
    [self.ControlView addSubview:self.buffer];
    [self.ControlView addSubview:self.timeSlider];
    
    //开始时间
    self.startTimeLabel = [[UILabel alloc] init];
    self.startTimeLabel.text = @"00:00";
    self.startTimeLabel.frame = CGRectMake(10, self.ControlView.frame.size.height - 35, 40, 20);
    self.startTimeLabel.font = [UIFont systemFontOfSize:13];
    self.startTimeLabel.textColor = [UIColor lightGrayColor];
    [self.ControlView addSubview:self.startTimeLabel];
//    self.startTimeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    //总时间
    self.allTimeLabel = [[UILabel alloc] init];
    self.allTimeLabel.text = @"00:00";
    self.allTimeLabel.textColor = [UIColor lightGrayColor];
    self.allTimeLabel.font = [UIFont systemFontOfSize:13];
    self.allTimeLabel.frame = CGRectMake(self.ControlView.frame.size.width - 40, self.ControlView.frame.size.height - 35, 40, 20);
    [self.ControlView addSubview:self.allTimeLabel];
//    self.allTimeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    //返回button
    self.backButton = [[UIButton alloc] init];
    self.backButton.frame = CGRectMake(20, 0, 350, 50);
    
    [self.backButton addTarget:self action:@selector(BackButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.ControlView addSubview:self.backButton];
    
    
    UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back.png"]];
    image2.frame = CGRectMake(0, 10, 20, 20);
    [self.backButton addSubview:image2];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.frame = CGRectMake(20, 10, 400, 20);
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.receiveModel.title;
    [self.backButton addSubview:self.titleLabel];
    
    //音量加button
    self.volumeUpbutton = [[UIButton alloc] init];
    self.volumeUpbutton.frame = CGRectMake(25, 90, 15, 15);
    [self.volumeUpbutton setImage:[UIImage imageNamed:@"volume"] forState:UIControlStateNormal];
    [self.ControlView addSubview:self.volumeUpbutton];
    [self.volumeUpbutton addTarget:self action:@selector(volumeUp:) forControlEvents:UIControlEventTouchUpInside];
    
    //声音进度条
    self.progress = [[UIProgressView alloc]initWithProgressViewStyle: UIProgressViewStyleBar];
    self.progress.backgroundColor = [UIColor grayColor];
    self.progress.progressTintColor = [UIColor whiteColor];
    self.progress.progress = 1;
    self.progress.frame = CGRectMake(-26, 175, 110, 15);
    
    CGAffineTransform trans = CGAffineTransformMakeRotation(M_PI / 2 * 3);
    self.progress.transform = trans;
    [self.ControlView addSubview:self.progress];
    
    //音量减button
    self.volumeDownbutton = [[UIButton alloc] init];
    self.volumeDownbutton.frame = CGRectMake(25, 242, 15, 15);
    [self.volumeDownbutton setImage:[UIImage imageNamed:@"volumeSmall"] forState:UIControlStateNormal];
    [self.ControlView addSubview:self.volumeDownbutton];
    [self.volumeDownbutton addTarget:self action:@selector(volumeDown:) forControlEvents:UIControlEventTouchUpInside];
    
    //收藏Button
    self.CollectButton = [[UIButton alloc] init];
    self.CollectButton.frame = CGRectMake(self.ControlView.frame.size.width - 100, 7, 25, 25);
    [self.CollectButton setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
    [self.CollectButton addTarget:self action:@selector(collectButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
//    self.CollectButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ControlView addSubview:self.CollectButton];
    
//    //上传Button
//    self.uploadButton = [[UIButton alloc] init];
//    [self.uploadButton setImage:[UIImage imageNamed:@"上传白.png"] forState:UIControlStateNormal];
//    self.uploadButton.frame = CGRectMake(self.ControlView.frame.size.width - 50, 7, 25, 25);
////    self.uploadButton.translatesAutoresizingMaskIntoConstraints = NO;
//    [self.ControlView addSubview:self.uploadButton];
    
    //暂停button
    self.pauseButton = [[UIButton alloc] init];
    [self.pauseButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
    self.pauseButton.frame = CGRectMake(screenFrame.size.height / 2 - 22, screenFrame.size.width / 2 - 22, 44, 44);
    [self.pauseButton addTarget:self action:@selector(pauseButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.ControlView addSubview:self.pauseButton];

    //在控件层加手势
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGRAction:)];
    //需要手指的个数
    tapGR.numberOfTouchesRequired = 1;
    [_ControlView addGestureRecognizer:tapGR];
    //在视频层加手势
    UITapGestureRecognizer *movietapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(movietapGRAction:)];
    movietapGR.numberOfTouchesRequired = 1;
    [self.movieView addGestureRecognizer:movietapGR];
    
    //初始化控件
    self.allTimeLabel.text = self.playAllTime;
}


//在控件层加手势
- (void)tapGRAction:(UITapGestureRecognizer *)sender{
    
    
    self.ControlView.hidden = 1;
    self.shadeView.hidden = 1;
}


//在视频层加手势
- (void)movietapGRAction:(UITapGestureRecognizer *)sender{
    self.ControlView.hidden = 0;
    self.shadeView.hidden = 0;
}



//收藏button点击事件
- (void)collectButtonDidClicked:(UIButton *)sender{
    [sender setShowsTouchWhenHighlighted:1];
    if (!self.isCollect) {
        
        
        [self.CollectButton setBackgroundImage:[UIImage imageNamed:@"liked"] forState:UIControlStateNormal];
        self.isCollect = 1;
        [[DataBaseHandle shareDataBaseHandle] insertStudent:self.receiveModel];
    }else{
        [self.CollectButton setBackgroundImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
        self.isCollect = 0;
        [[DataBaseHandle shareDataBaseHandle] deleteWithModel:self.receiveModel];
    }
}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.arrCollect = [NSMutableArray array];
    self.arrCollect = [[DataBaseHandle shareDataBaseHandle] select].mutableCopy;
    
    for (MovieModel *model in self.arrCollect) {
        if ([model.title isEqualToString:_receiveModel.title]) {
            
            [_CollectButton setBackgroundImage:[UIImage imageNamed:@"liked"] forState:UIControlStateNormal];
            _isCollect = 1;
            break;
            
        }else{
            [_CollectButton setBackgroundImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
            _isCollect = 0;
        }
    }
}


//返回Button点击事件
- (void)BackButtonDidClicked:(UIButton *)sender{
    
    [self dismissViewControllerAnimated:1 completion:^{
        
        
    }];

}


//音量加
- (void)volumeUp:(UIButton *)sender{
    [sender setShowsTouchWhenHighlighted:1];
    if(self.player.volume < 2){
        self.player.volume += 0.1;
    }else{
        self.player.volume = 2;
    }
    self.progress.progress = self.player.volume/2;
}



//声音减
- (void)volumeDown:(UIButton *)sender{
    [sender setShowsTouchWhenHighlighted:1];
    if (self.player.volume > 0) {
        self.player.volume-=0.1;
    }else{
        self.player.volume = 0;
    }
    self.progress.progress = self.player.volume/2;
}



//暂停Button点击事件
- (void)pauseButtonDidClicked:(UIButton *)sender{
    [sender setShowsTouchWhenHighlighted:1];
    if (!self.isPause) {
        [self.pauseButton setImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
        [self.player pause];
        self.adView.hidden = 0;
        self.isPause = 1;
        
        
        
    }else{
        [self.pauseButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [self.player play];
        self.adView.hidden = 1;
        self.isPause = 0;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(refondContr:) userInfo:nil repeats:NO];
    }
}


//收回控制器
- (void)refondContr:(NSTimer *)sender{
    self.ControlView.hidden = 1 ;
    self.shadeView.hidden = 1;
    
}


//timeSlider更新
- (void)UpdateTimeSlider:(NSTimer *)sender{
}


//监听player属性
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            if( [UIApplication sharedApplication].applicationState == UIApplicationStateActive ||  [UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
                [SVProgressHUD dismiss];
                [self.player play];
            }
            else {
                [self.player pause];
            }
            self.ControlView.hidden = 1;
            self.shadeView.hidden = 1;
            [self monitoringPlayback:self.player.currentItem];
            
            self.timeScale = playerItem.currentTime.timescale;
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
        CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval result = startSeconds + durationSeconds;
        
        float bufferProgress = (float)result / self.player.currentItem.duration.value * self.player.currentItem.duration.timescale;
        self.buffer.progress = bufferProgress;
    }
}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem{
    
    __weak VCForMVPlayerOfFirst *blockSelf = self;
    _obj = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0 / 60.0, NSEC_PER_SEC) queue:NULL usingBlock:^(CMTime time)
            {
                CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;
                _currentTime = currentSecond;
                double t = CMTimeGetSeconds(blockSelf.player.currentTime);
                blockSelf.timeSlider.value = t;
                
                blockSelf. startTimeLabel.text = [blockSelf getTtime:blockSelf.currentTime];
            }];
    if (_obj) {
        return;
    }
}



//timeSlider绑定事件
- (void)changeProgress:(UISlider *)sender{
    [self.player pause];
    CMTime cmtime= CMTimeMakeWithSeconds(sender.value, self.player.currentTime.timescale);
    
    [self.player seekToTime:cmtime completionHandler:^(BOOL finished) {
        //
        if (finished) {
            [self.player play];
            [_pauseButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
            [self.player play];
            self.adView.hidden = 1;
            self.isPause = 0;
        }
    }];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
- (NSString *)getTtime:(NSInteger)time {
    NSInteger min;
    NSInteger sec;
    min = time / 60;
    sec = time % 60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld",(long)min,(long)sec];
}
-(NSString *)getTime:(NSInteger)time {
    NSInteger min;
    NSInteger sec;
    min = time / 60;
    sec = time % 60;
    return [NSString stringWithFormat:@"%.2ld'%.2ld\"",(long)min,(long)sec];
}
- (void)viewWillDisappear:(BOOL)animated{
    [self.player pause];
    [self.player setRate:0];
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [self.timer invalidate];
    self.timer = nil;
    self.player = nil;
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(remove:) userInfo:nil repeats:NO];
    self.timer = time;
}

- (void)remove:(NSTimer *)sender{
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - 懒加载
-(UIProgressView *)buffer{
    if (_buffer == nil) {
        _buffer = [[UIProgressView alloc]init];
        //_buffer.backgroundColor = [UIColor clearColor];
        _buffer.progressTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.3];
        _buffer.trackTintColor = [UIColor clearColor];
        [self.ControlView insertSubview:_buffer belowSubview:_timeSlider];
        _buffer.translatesAutoresizingMaskIntoConstraints = NO;
        self.views = NSDictionaryOfVariableBindings(_buffer);
        [_ControlView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[_buffer]-50-|" options:0 metrics:nil views:_views]];
        [_ControlView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_buffer(2.0)]-23-|" options:0 metrics:nil views:_views]];
        
    }
    return _buffer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
